import sensor, image, time
from pyb import UART
from pyb import LED


LED(1).on()
LED(2).on()
LED(3).on()


sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)
sensor.set_windowing((0,0,160,80))#主车要缩小竖向缩小窗口
sensor.set_auto_whitebal(False)
sensor.set_auto_gain(False)
sensor.skip_frames(time = 2000)



uart=UART(3,9600)
uart.init(9600, bits=8, parity=None, stop=1)



clock = time.clock()



while(True):
    clock.tick()
    img = sensor.snapshot().lens_corr(1.8)
    hist = img.histogram()
    thresh = hist.get_threshold()[0]
    img.binary([(thresh,255)],invert=True)
    lin = img.get_regression([(100,255)])
    if(lin):
        rho_err = abs(lin.rho())-80

        if(rho_err>127):
            rho_err = 127
        if(rho_err<-128):
            rho_err = -128

        uart.write(bytearray([int(rho_err)]))
        #print('%d'%int(rho_err))
    #print(clock.fps())



